<template>
  <div class="usdt-list-container">
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline label-width="80px">
        <el-form-item label="订单号">
          <el-input
            v-model="searchForm.orderID"
            placeholder="请输入订单号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.userName"
            placeholder="请输入用户名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="管理员">
          <el-input
            v-model="searchForm.managerName"
            placeholder="请输入管理员名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="地址">
          <el-input
            v-model="searchForm.address"
            placeholder="请输入支付地址"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.state"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待处理" :value="0" />
            <el-option label="已完成" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额范围">
          <el-input-number
            v-model="searchForm.amount[0]"
            placeholder="最小金额"
            :min="0"
            style="width: 120px"
          />
          <span style="margin: 0 10px">-</span>
          <el-input-number
            v-model="searchForm.amount[1]"
            placeholder="最大金额"
            :min="0"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="ctimeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
            style="width: 350px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <!-- 操作按钮 -->
      <div class="action-area mb-20">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增出金
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="orderID" label="订单号" width="180" />
        <el-table-column prop="userName" label="用户名" width="100" />
        <el-table-column prop="amount" label="申请金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">{{ formatAmount(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="rateAmount" label="实际金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">{{ formatAmount(row.rateAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="payAddress" label="支付地址" width="160">
          <template #default="{ row }">
            <el-tooltip :content="row.payAddress" placement="top">
              <span class="address-text">{{
                truncateAddress(row.payAddress)
              }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="managerName" label="管理员" width="120" />
        <el-table-column prop="state" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStateType(row.state)">
              {{ getStateText(row.state) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.cTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="uTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.uTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150">
          <template #default="{ row }">
            <el-tooltip
              :content="row.remark"
              placement="top"
              :disabled="!row.remark"
            >
              <span>{{ row.remark || "-" }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button type="primary" size="mini" @click="handleAction(row)">
              操作
            </el-button>
            <!-- <el-button type="danger" size="mini" @click="handleDelete(row)">
              删除
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增出金 -->
    <el-dialog
      title="新增出金"
      v-model="dialogVisible"
      width="50%"
      @close="handleCancel"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef">
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="金额" prop="usdt">
          <el-input v-model="formData.usdt" placeholder="请输入金额" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </template>
    </el-dialog>
    <!-- 出金操作 -->
    <el-dialog
      title="出金操作"
      v-model="actionDialogVisible"
      width="50%"
      @close="handleClose"
    >
      <el-form
        :model="actionFormData"
        :rules="actionFormRules"
        ref="actionFormRef"
        label-width="100px"

      >
        <el-form-item label="汇率" prop="rate">
          <el-input
            v-model="actionFormData.rate"
            placeholder="请输入出金汇率"
          />
        </el-form-item>
        <el-form-item label="验证码" prop="secretCode">
          <el-input
            v-model="actionFormData.secretCode"
            placeholder="请输入验证码"
          />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="actionFormData.state" placeholder="请选择状态">
            <el-radio :label=0>通过</el-radio>
            <el-radio :label=1>拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="actionFormData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitActionForm">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getOutUsdtList, createOutUsdt, rejectOutUsdt } from "@/api/system";
import { ref, onMounted, computed, reactive } from "vue";
import { OutUsdtList } from "@/api/types";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";

const loading = ref(false);
const tableData = ref<OutUsdtList[]>([]);
const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
});

// 出金操作
// 控制弹窗显隐
const actionDialogVisible = ref(false);
// 出金操作表单
const actionFormRef = ref<FormInstance>();
const actionFormData = reactive({
  id: 0,
  rate: 0,
  remark: "",
  secretCode: "",
  state: 0,
});
const actionFormRules: FormRules = {
  rate: [{ required: true, message: "请输入汇率", trigger: "blur" }],
  secretCode: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  state: [{ required: true, message: "请选择状态", trigger: "blur" }],
};
// 关闭弹窗
const handleClose = () => {
  actionFormRef.value?.resetFields();
  actionFormData.id = 0;
  actionFormData.rate = 0;
  actionFormData.remark = "";
  actionFormData.secretCode = "";
  actionFormData.state = 0;
  actionDialogVisible.value = false;
};

// 打开弹窗
const handleAction = (row: OutUsdtList) => {
  console.log(row);
  actionFormData.id = row.id;
  actionDialogVisible.value = true;
};
// 提交出金操作表单
const submitActionForm = async () => {
  if (!actionFormRef.value) return;
  await actionFormRef.value.validate();
  actionFormData.rate = Number(actionFormData.rate);

  try {
    const res = await rejectOutUsdt(actionFormData);
    console.log(res);
    ElMessage.success("操作成功");
    actionDialogVisible.value = false;
    actionFormRef.value.resetFields();
    fetchData();
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 新增出金对话框
const dialogVisible = ref(false);
// 新增出金表单
const formRef = ref<FormInstance>();
const formData = reactive({
  address: "",
  usdt: 0,
});

// 新增出金表单校验规则
const formRules: FormRules = {
  address: [{ required: true, message: "请输入地址", trigger: "blur" }],
  usdt: [{ required: true, message: "请输入金额", trigger: "blur" }],
};

const searchForm = ref({
  address: "",
  amount: [null, null] as [number | null, number | null],
  managerName: "",
  orderID: "",
  state: null as number | null,
  userName: "",
});

const ctimeRange = ref<[number, number] | null>(null);

// 计算属性：处理时间范围
const ctimeDateRange = computed(() => {
  return ctimeRange.value ? [ctimeRange.value[0], ctimeRange.value[1]] : [];
});

// 打开新增弹窗
const handleAdd = () => {
  dialogVisible.value = true;
  formRef.value?.resetFields();
};

// 关闭弹窗
const handleCancel = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  formData.usdt = Number(formData.usdt);
  try {
    const res = await createOutUsdt(formData);
    console.log(res);

    ElMessage.success("新增成功");
    dialogVisible.value = false;
    formRef.value.resetFields();
    fetchData();
  } catch (error) {
    console.error("新增失败:", error);
    ElMessage.error("新增失败");
  }
};

// 获取列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.page,
      size: pagination.value.size,
      address: searchForm.value.address || undefined,
      amount:
        searchForm.value.amount.filter((item) => item !== null).length > 0
          ? (searchForm.value.amount.filter(
              (item) => item !== null
            ) as number[])
          : undefined,
      ctimeDateRange:
        ctimeDateRange.value.length > 0 ? ctimeDateRange.value : undefined,
      managerName: searchForm.value.managerName || undefined,
      orderID: searchForm.value.orderID || undefined,
      state: searchForm.value.state,
      userName: searchForm.value.userName || undefined,
    };

    const response = await getOutUsdtList(params);
    tableData.value = response.data.data;
    pagination.value.total = response.data.total;
  } catch (error) {
    console.error("获取USDT出金列表失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.value.page = 1;
  fetchData();
};

// 重置
const handleReset = () => {
  searchForm.value = {
    address: "",
    amount: [null, null],
    managerName: "",
    orderID: "",
    state: null,
    userName: "",
  };
  ctimeRange.value = null;
  pagination.value.page = 1;
  fetchData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.value.size = size;
  pagination.value.page = 1;
  fetchData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  fetchData();
};

// 格式化金额
const formatAmount = (amount: number) => {
  return new Intl.NumberFormat("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 6,
  }).format(amount);
};

// 格式化时间
const formatTime = (timestamp: number) => {
  if (!timestamp) return "-";
  return new Date(timestamp).toLocaleString("zh-CN");
};

// 截断地址显示
const truncateAddress = (address: string) => {
  if (!address) return "-";
  if (address.length <= 20) return address;
  return `${address.slice(0, 10)}...${address.slice(-10)}`;
};

// 获取状态类型
const getStateType = (state: number) => {
  const typeMap: Record<number, string> = {
    0: "warning",
    1: "success",
    2: "danger",
  };
  return typeMap[state] || "info";
};

// 获取状态文本
const getStateText = (state: number) => {
  const textMap: Record<number, string> = {
    0: "待审核",
    1: "已完成",
    2: "已拒绝",
  };
  return textMap[state] || "未知";
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.usdt-list-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.amount-text {
  font-weight: 600;
  color: #409eff;
}

.address-text {
  font-family: monospace;
  font-size: 12px;
  cursor: pointer;
}

.address-text:hover {
  color: #409eff;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>
